Skip to content

Conversation

@MannXo
Copy link

@MannXo MannXo commented Oct 22, 2025

What do these changes do?

Adapt async context managers to behave like single-yield async iterators.

1- Allow app.cleanup_ctx callbacks to return either:
a single-yield async generator (existing behavior), or
an async context manager (e.g. @contextlib.asynccontextmanager).

2- Internally adapt async context managers with a small adapter so:
__aenter__ runs at startup (equivalent to the generator yielding), and
__aexit__ runs at cleanup (equivalent to finishing the generator).

3- Preserve previous cleanup/error aggregation semantics.

Are there changes in behavior for the user?

No breaking changes; this is fully backwards compatible.

  • Existing async-generator cleanup contexts continue to work unchanged.
  • New: callers may pass contextlib.asynccontextmanager instances for cleanup contexts.

Is it a substantial burden for the maintainers to support this?

No

Related issue number

Closes #11681

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
    • The format is <Name> <Surname>.
    • Please keep alphabetical order, the file is sorted by names.
  • Add a new news fragment into the CHANGES/ folder
    • name it <issue_or_pr_num>.<type>.rst (e.g. 588.bugfix.rst)

    • if you don't have an issue number, change it to the pull request
      number after creating the PR

      • .bugfix: A bug fix for something the maintainers deemed an
        improper undesired behavior that got corrected to match
        pre-agreed expectations.
      • .feature: A new behavior, public APIs. That sort of stuff.
      • .deprecation: A declaration of future API removals and breaking
        changes in behavior.
      • .breaking: When something public is removed in a breaking way.
        Could be deprecated in an earlier release.
      • .doc: Notable updates to the documentation structure or build
        process.
      • .packaging: Notes for downstreams about unobvious side effects
        and tooling. Changes in the test invocation considerations and
        runtime assumptions.
      • .contrib: Stuff that affects the contributor experience. e.g.
        Running tests, building the docs, setting up the development
        environment.
      • .misc: Changes that are hard to assign to any of the above
        categories.
    • Make sure to use full sentences with correct case and punctuation,
      for example:

      Fixed issue with non-ascii contents in doctest text files
      -- by :user:`contributor-gh-handle`.

      Use the past tense or the present tense a non-imperative mood,
      referring to what's changed compared to the last released version
      of this project.

…\nAdapt async context managers to behave like single-yield async iterators and add tests.
@psf-chronographer psf-chronographer bot added the bot:chronographer:provided There is a change note present in this PR label Oct 22, 2025
@codspeed-hq
Copy link

codspeed-hq bot commented Oct 22, 2025

CodSpeed Performance Report

Merging #11704 will not alter performance

Comparing MannXo:feature/accept-async-context-manager-for-cleanup-context (5f5dd32) with master (1fbb1bb)

Summary

✅ 59 untouched

@codecov
Copy link

codecov bot commented Oct 22, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.73%. Comparing base (1fbb1bb) to head (5f5dd32).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff            @@
##           master   #11704    +/-   ##
========================================
  Coverage   98.73%   98.73%            
========================================
  Files         127      127            
  Lines       43546    43646   +100     
  Branches     2320     2323     +3     
========================================
+ Hits        42996    43095    +99     
  Misses        390      390            
- Partials      160      161     +1     
Flag Coverage Δ
CI-GHA 98.61% <100.00%> (+<0.01%) ⬆️
OS-Linux 98.34% <100.00%> (+<0.01%) ⬆️
OS-Windows 96.68% <100.00%> (+<0.01%) ⬆️
OS-macOS 97.56% <100.00%> (+<0.01%) ⬆️
Py-3.10.11 97.11% <100.00%> (+<0.01%) ⬆️
Py-3.10.18 97.61% <100.00%> (+<0.01%) ⬆️
Py-3.11.13 97.81% <100.00%> (+<0.01%) ⬆️
Py-3.11.9 97.32% <100.00%> (-0.01%) ⬇️
Py-3.12.10 97.42% <100.00%> (+<0.01%) ⬆️
Py-3.12.11 97.91% <100.00%> (+<0.01%) ⬆️
Py-3.13.7 97.91% <100.00%> (-0.01%) ⬇️
Py-3.13.9 97.40% <100.00%> (-0.01%) ⬇️
Py-3.14.0 98.13% <100.00%> (+0.01%) ⬆️
Py-3.14.0t 97.19% <100.00%> (+0.01%) ⬆️
Py-pypy3.10.16-7.3.19 92.28% <100.00%> (-3.09%) ⬇️
VM-macos 97.56% <100.00%> (+<0.01%) ⬆️
VM-ubuntu 98.34% <100.00%> (+<0.01%) ⬆️
VM-windows 96.68% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment on lines 454 to 456
# If the callback returned an async context manager (has
# __aenter__ and __aexit__), wrap it so it behaves like an
# async iterator that yields once.
Copy link
Member

@Dreamsorcerer Dreamsorcerer Oct 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make more sense to make context managers our de facto default now? Surely then all we need to do for backwards compatibility is:

if not isinstance(ctx, AbstractAsyncContextManager):
    ctx = asynccontextmanager(ctx)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pushed a fix making it the default.

Copy link
Member

@Dreamsorcerer Dreamsorcerer Oct 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I mean that the code should should be changed to use aenter/aexit instead of anext. Then we don't need the awkward _AsyncCMAsIterator class and much of the other code becomes much simpler.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • removed the _AsyncCMAsIterator
  • replaced the adapter-based approach with direct use of aenter/aexit for async context managers.
    CleanupContext now:
  • If cb returns an AsyncIterator: advances it once on startup and finishes it on cleanup (legacy).
  • If cb returns an AbstractAsyncContextManager: calls aenter on startup and aexit on cleanup.
  • If cb returns something else: adapts it via contextlib.asynccontextmanager, calls aenter/aexit.

@Dreamsorcerer Dreamsorcerer added the backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot label Oct 22, 2025
@webknjaz webknjaz requested a review from bdraco October 22, 2025 20:55
Comment on lines 459 to 485
# If the callback returned an async iterator (legacy async
# generator), use it directly. If it returned an async
# context manager instance, enter it and remember the manager
# for later exit. As a final fallback, convert the callback
# into an async context manager (covers some edge cases) and
# enter that.
if isinstance(ctx, AsyncIterator):
# Legacy async generator cleanup context: advance it once
# (equivalent to entering) and remember the iterator for
# finalization.
it = cast(AsyncIterator[None], ctx)
await it.__anext__()
self._exits.append(it)
elif isinstance(ctx, contextlib.AbstractAsyncContextManager):
# If ctx is an async context manager: enter it and
# remember the manager for later exit.
cm = ctx
await cm.__aenter__()
self._exits.append(cm)
else:
# cb may have a broader annotated return type; adapt the
# callable into an async context manager and enter it.
cm = contextlib.asynccontextmanager(
cast(Callable[[Application], AsyncIterator[None]], cb)
)(app)
await cm.__aenter__()
self._exits.append(cm)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mentioned originally, can't this be reduced to just this?

Suggested change
# If the callback returned an async iterator (legacy async
# generator), use it directly. If it returned an async
# context manager instance, enter it and remember the manager
# for later exit. As a final fallback, convert the callback
# into an async context manager (covers some edge cases) and
# enter that.
if isinstance(ctx, AsyncIterator):
# Legacy async generator cleanup context: advance it once
# (equivalent to entering) and remember the iterator for
# finalization.
it = cast(AsyncIterator[None], ctx)
await it.__anext__()
self._exits.append(it)
elif isinstance(ctx, contextlib.AbstractAsyncContextManager):
# If ctx is an async context manager: enter it and
# remember the manager for later exit.
cm = ctx
await cm.__aenter__()
self._exits.append(cm)
else:
# cb may have a broader annotated return type; adapt the
# callable into an async context manager and enter it.
cm = contextlib.asynccontextmanager(
cast(Callable[[Application], AsyncIterator[None]], cb)
)(app)
await cm.__aenter__()
self._exits.append(cm)
if not isinstance(ctx, contextlib.AbstractAsyncContextManager):
ctx = contextlib.asynccontentmanager(cb)(app)
await ctx.__aenter__()
self._exits.append(ctx)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to reduce it to your suggested version, but I think it changes semantics in a way that breaks cleanup-context lifecycle invariants. We end up with two generator instances because we also call ctx = cb(app) before wrapping, the net effect is that cb(app) is invoked twice in the fallback path:
1- ctx = cb(app) first call
2- contextlib.asynccontextmanager(cb)(app) second call

For async-generator style cleanup callbacks this yields two generator instances. The instance you advance on startup is not the same instance you finalize on cleanup.

I might have missunderstood your comment. Did you intend to change semantics so that cb may be invoked more than once? or did you mean to wrap the returned value when it’s not a context manager?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the net effect is that cb(app) is invoked twice

Yes, I had realised that, but not sure it causes any actual problems. We can then probably deprecate the generator fallback in future to remove this, after a couple of years.

The instance you advance on startup is not the same instance you finalize on cleanup.

That shouldn't be true. The second instance replaces the first one before it is used. So, if the first instance is a generator object, it gets discarded without being used at all. The second instance is then used for both startup and cleanup.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

applied your suggestion.
ready for the next review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accepting async context managers for cleanup contexts

3 participants